package com.zretc.activity.service.impl;


import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zretc.activity.mapper.ActivityContentMapper;
import com.zretc.activity.mapper.ActivityMapper;
import com.zretc.activity.mapper.ParMapper;
import com.zretc.activity.service.ActivityService;
import com.zretc.api.pojo.activityModule.dtos.ActivityDto;
import com.zretc.api.pojo.activityModule.pojos.Activity;
import com.zretc.api.pojo.activityModule.pojos.ActivityContent;
import com.zretc.api.pojo.activityModule.pojos.Participation;
import com.zretc.common.constant.WebConstant;
import com.zretc.common.entity.R;
import com.zretc.common.entity.RespResult;
import com.zretc.security.entity.LoginUser;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
@Transactional
public class ActivityServiceImpl extends ServiceImpl<ActivityMapper, Activity> implements ActivityService {
    @Autowired
    private ActivityContentMapper activityContentMapper;
    @Autowired
    private ParMapper parMapper;
    @Override
    public RespResult submit(ActivityDto activityDto) {
        if(activityDto == null) {
            return R.fail(405, WebConstant.ERROR_405);
        }
        Activity activity = new Activity();
        BeanUtils.copyProperties(activityDto, activity);
        if(activityDto.getId() == null) {//id不存在，上传活动
            LoginUser loginUser = (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            activity.setInitId(loginUser.getUser().getId());
            activity.setInitName(loginUser.getUser().getNick_name());
            activity.setCreateTime(new Date());
            save(activity);
            ActivityContent activityContent = new ActivityContent(activity.getId(),activityDto.getContent());
            activityContentMapper.insert(activityContent);
        }else {//id存在，更新活动
            updateById(activity);
            ActivityContent activityContent = new ActivityContent(activity.getId(),activityDto.getContent());
            activityContentMapper.update(activityContent,Wrappers.<ActivityContent>lambdaQuery()
                    .eq(ActivityContent::getActivityId,activityDto.getId()));
        }
        return R.success(null);
    }

    @Override
    public RespResult getByType(String type) {
         List<Activity> list = list(Wrappers.<Activity>lambdaQuery()
                    .eq(Activity::getType, type)
                    .eq(Activity::getIsDeleted, 0)
                    .eq(Activity::getStatus, 1));
        return R.success(list);
    }

    @Override
    public RespResult getActivityDetails(ActivityDto activityDto) {
        //添加内容
        ActivityContent activityContent = activityContentMapper.selectOne(Wrappers.<ActivityContent>lambdaQuery()
                .eq(ActivityContent::getActivityId, activityDto.getId()));
        activityDto.setContent(activityContent.getContent());
        //添加当前用户是否参加
        LoginUser loginUser = (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        Participation participation = parMapper.selectOne(Wrappers.<Participation>lambdaQuery()
                .eq(Participation::getActivityId, activityDto.getId())
                .eq(Participation::getUserId, loginUser.getUser().getId()));
        if(participation == null){
            activityDto.setIsPar(0);
        }else {
            if(participation.getIsDeleted() == 0){
                activityDto.setIsPar(1);
            }else {
                activityDto.setIsPar(2);
            }
        }
        return R.success(activityDto);
    }

    @Override
    @Transactional
    public RespResult participate(ActivityDto activityDto) {
        LoginUser loginUser = (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if(parMapper.selectOne(Wrappers.<Participation>lambdaQuery()
                .eq(Participation::getActivityId, activityDto.getId())
                .eq(Participation::getUserId, loginUser.getUser().getId())) == null) {//数据库中没有申请
            boolean success = update()
                    .setSql("remain_number = remain_number - 1")
                    .eq("id", activityDto.getId())
                    .gt("remain_number", 0)
                    .update();
            if(success){//还有剩余人数
                Participation participation = new Participation(activityDto.getId(),loginUser.getUser().getId());
                participation.setActivityName(activityDto.getActivityName());
                participation.setStartTime(activityDto.getStartTime());
                participation.setLocation(activityDto.getLocation());
                parMapper.insert(participation);
            }else{
                return R.success("人数已满");
            }
        }else {
            return R.success("不允许重复报名");
        }
        return R.success("报名成功");
    }

    @Override
    public RespResult cancel(ActivityDto activityDto) {
        LoginUser loginUser = (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        Participation participation = parMapper.selectOne(Wrappers.<Participation>lambdaQuery()
                .eq(Participation::getActivityId, activityDto.getId())
                .eq(Participation::getUserId, loginUser.getUser().getId()));
        if(participation.getIsDeleted() == 0) {//数据库中有数据且没被删除
            //恢复一个名额
            update().setSql("remain_number = remain_number + 1")
                    .eq("id", activityDto.getId())
                    .update();
            participation.setIsDeleted(1);
            parMapper.updateById(participation);
        }

        return R.success("取消成功");
    }

    @Override
    public RespResult delete(ActivityDto activityDto) {
        Activity activity = new Activity();
        activity.setId(activityDto.getId());
        activity.setIsDeleted(1);
        //删除活动
        updateById(activity);
        List<Participation> participations = parMapper.selectList(Wrappers.<Participation>lambdaQuery()
                .eq(Participation::getActivityId, activityDto.getId()));
        for(Participation participation : participations) {//删除活动报名
            participation.setIsDeleted(1);
            parMapper.updateById(participation);
        }
        ActivityContent activityContent = new ActivityContent();
        activityContent.setActivityId(activityDto.getId());
        activityContent.setIsDeleted(1);
        //删除活动内容
        activityContentMapper.update(activityContent,Wrappers.<ActivityContent>lambdaQuery()
                .eq(ActivityContent::getActivityId,activityDto.getId()));
        return R.success("删除成功");
    }

}
